/*
 * @lc app=leetcode.cn id=25 lang=golang
 *
 * [25] K 个一组翻转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func reverseKGroup(head *ListNode, k int) *ListNode {
	node := &ListNode{Val: -1, Next: head}
	ptr := node
	for head != nil {
		pre, next := reverseK(head, k)
		ptr.Next = pre
		if next != nil {
			head = next.Next
		} else {
			head = next
		}
		ptr = next
	}
	return node.Next
}
func reverseK(head *ListNode, k int) (*ListNode, *ListNode) {
	if head == nil {
		return nil, nil
	}
	ptr := head
	t := k
	for ptr != nil && t != 0 {
		ptr = ptr.Next
		t--
	}
	if t != 0 {
		return head, nil
	}

	pre := &ListNode{Val: -1, Next: head}
	next := pre
	for k > 0 {
		temp := head
		head = head.Next

		temp.Next = pre.Next
		pre.Next = temp
		next = next.Next
		k--
	}
	next.Next = head
	return pre.Next, next
}

// @lc code=end

